define([
    'base',
    'bootstrapDialog',
    'bootstrapTable',
    'plugins/ztree/ztree'
], function (base,BootstrapDialog) {
    //默认加载基础库
    base();

    return {
        list: function () {
            var myTable = $('#adminOrgList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'api.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'api.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("编辑", row);
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '组织机构',
                        nameValue: row.orgName,
                        url: '../status/action'
                    });
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '组织机构',
                        nameValue: row.orgName,
                        url: '../delete/action'
                    });
                }
            };

            //table表格
            myTable.bootstrapTable({
                url: 'api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [{ // 列设置
                    field: 'state',
                    checkbox: true // 使用复选框
                },
                    {
                        field: 'id',
                        title: '编号'
                    }, {
                        field: 'orgName',
                        title: '名称'
                    }, {
                        field: 'parentName',
                        title: '父类名称',
                        formatter: function (value, row, index) {
                            if (value === null || value === '') {
                                return '根节点';
                            } else {
                                return value;
                            }
                        }
                    }, {
                        field: 'orgCode',
                        title: '组织代码'
                    },
                    {
                        field: 'orgType',
                        title: '类型',
                        formatter: function (value, row, index) {
                            var result = null;
                            switch (value) {
                                case 1:
                                    result = "组织机构";
                                    break;
                                case 2:
                                    result = "组织部门";
                                    break;
                                case 3:
                                    result = "部门小组";
                                    break;
                                default:
                                    result = "未知";
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'sort',
                        title: '排列'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center',
                        formatter: function (value, row, index) {
                            if (value == 1) {
                                return '<span class="label label-primary">正常</span>';
                            } else {
                                return '<span class="label label-danger">已禁</span>';
                            }
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            // 初始化slimscroll右栏
            $('#sideTree').slimScroll({
                height: 580,
                railOpacity: 0.4,
                wheelStep: 5,
                color: '#18212A',
                opacity: .5,
                railVisible: true
            });


            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

            //toolbar按钮相应事件
            //新增
            $(".toolbar-save").on('click', function () {
                winModal("新增", null);
            });
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.orgName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '组织机构菜单',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }


            //左侧资源导航ztree插件
            $.baseUtils.tree({
                treeNodeName: "#navTree",
                ajaxUrl: "tree/0",
                isAction: true,
                doAction: doAction
            });

            //ztree插件链接点击刷新全部
            $("#allResList").on('click', function () {
                tableRefresh();
            });

            //模态框
            function winModal(title, row) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('../save/form.html'),
                    data: {
                        'row': row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = false;
                            flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '../save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#adminOrgList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function (dialog) {
                        //下拉插件
                        var orgSelect = $.baseUtils.select({
                            cssName: "#pid",
                            dataName: "orgName",
                            url: "orgSelect.json",
                            minimumResultsForSearch: 0,
                            templateResult: templateResult
                        });

                        //重写数据列表模板
                        function templateResult(repo) {
                            if (repo.loading) return repo.text;
                            var result = "";
                            switch (repo.orgType) {
                                case 1://1是组织架构
                                    result += "<i class=\"fa fa-chevron-right\" aria-hidden=\"true\"></i>&nbsp;<strong>" + repo.orgName + "</strong>";
                                    break;
                                case 2://2是组织部门
                                    result += "&nbsp;&nbsp;<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i>&nbsp;" + repo.orgName;
                                    break;
                                case 3://3是部门小组
                                    result += "&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-angle-double-right\" aria-hidden=\"true\"></i>&nbsp;" + repo.orgName;
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }


                        if (row != null) {
                            //判断并设置select默认值
                            if (row.pid && row.parentName) {
                                orgSelect.append("<option value='" + row.pid + "'>" + row.parentName + "</option>");
                            }
                            $('input[name=orgType][value=' + row.orgType + ']').attr('checked', true);
                            $('#id').val(row.id);
                            $('#orgName').val(row.orgName);
                            $('#orgCode').val(row.orgCode);
                            $('#sort').val(row.sort);
                            $('#description').val(row.description);
                        }
                        ;

                    }
                });
            };
        },
        update: function () {

        }
    }
});






